package com.soft.controller;

import com.soft.entity.TCart;
import com.soft.entity.TProduct;
import com.soft.entity.TUser;
import com.soft.service.TCartService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.util.List;

/**
 * (TCart)表控制层
 *
 * @author makejava
 * @since 2021-12-25 04:03:29
 */
@Controller
@RequestMapping("/tCart")
public class TCartController {
    private TUser login;
    /**
     * 服务对象
     */
    @Resource
    private TCartService tCartService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public TCart selectOne(Integer id) {
        return this.tCartService.queryById(id);
    }

    @RequestMapping("/carts")
//    @ResponseBody
    public String carts(Model model, HttpSession session){
        login = (TUser) session.getAttribute("user");
        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(login.getId());
        TCartController.cartBar(list, model);
        return "user/cart";
//        return list;
    }
    public static  void cartBar(List<TCart> list ,Model model){
        Float totalMoney = 0.0f;
        Integer totalCount = 0;
        for(TCart tCart : list){
            totalMoney += tCart.getTProduct().getPrice()*tCart.getCount()*tCart.getTProduct().getDiscount();
            totalCount += tCart.getCount();
        }
        DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        String money = decimalFormat.format(totalMoney);
        model.addAttribute("totalMoney", money);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("cartList", list);
    }

    @RequestMapping("deleteCart")
    public String deleteProductByCartById(Integer id, Model model, HttpSession session){
        if(tCartService.deleteById(id)){
            model.addAttribute("msg", "ok");
        }else{
            model.addAttribute("msg", "删除失败！");
        }
//        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(4);//session
//        cartBar(list, model);
        return "redirect:/userCart";
    }
    @RequestMapping("checkout.html")
    public String checkout(){
        return "/user/checkout";
    }
}